﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using Service;
using Resources;

public partial class planningView : System.Web.UI.Page
{
   
     protected void Page_Load(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionViewPlanning))
        {
            lblMessageValidate.Text = Resource.Permission;
            lblTotalEquipment.Visible = false;
            grdGroupeSoftware1.Visible = false;
            grdEquipment.Visible = false;
            return;
        }

        
        if(Session["firstLoad"] == null)
        if (Request.QueryString["workOrderId"] != null)
        {
            txtWorkOrder.Text = Request.QueryString["workOrderId"];
            Session["whereClause"] = GetWhereClause();
            txtHiddenWhereClause.Text = GetWhereClause();
            Session["firstLoad"] = "false";
            
        }

         txtHiddenPlanningId.Text = Request.QueryString["planningId"];
        if (Session["whereClause"] == null)
            Session["whereClause"] = txtHiddenWhereClause.Text;
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;

        new Utility().SetRowToDisplay(grdEquipment, Session["rowsToSDisplay"]);
        lblInformation.Text = string.Empty;
        if (!IsPostBack)
        {

            Session["planningId"] = Request.QueryString["planningId"];
            Session["defaultTabIndex"] = Request.QueryString["tabIndex"];
            if (Request.QueryString["authorize"] != null)
            {
                int planningId = Request.QueryString["planningId"] != null ? Int32.Parse(Request.QueryString["planningId"]) : 0;
              
                txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
               

            }else 
            // to avoid loading for the first time
            if ((Request.QueryString["detail"] == null))
            {
                
            }
            else
            {
                txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
               
            }
            if (Session["pageIndex"] != null)
            {
                grdEquipment.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

            }
            if ((Request.QueryString["delete"] != null))
            {
                try
                {
                    PlanningService _PlanningService = new PlanningService();
                    _PlanningService.DeletePlanning(new Utility().ConvertToInteger(Session["planningId"]));
                    lblInformation.Text = string.Empty;

                }catch(Exception )
                {
                    lblInformation.Text = Resources.Resource.MsgDeletePlanningFailed; 
                }

            }
            
            txtHiddenPageIndex.Text = "0";
        }
        else txtHiddenPageIndex.Text = "0";
        grdEquipment.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;
    }
   
  
    public string GetTaskId()
    {
        string taskString = string.Empty;
        if (Request.QueryString["taskId"] != null)
            taskString = "&taskId="+Request.QueryString["taskId"];
        return taskString;
        
    }
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEquipment.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdEquipment.PageIndex.ToString();
        Session["pageIndex"] = grdEquipment.PageIndex;

    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        
    }
 
    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?Int32.Parse(Session["pageIndex"].ToString()): 0;
    }
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }
    public string GetDisplayMode()
    {
        return Request.QueryString["detail"];
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionViewPlanning))
        {
            lblMessageValidate.Text = Resource.Permission;
            lblTotalEquipment.Visible = false;
            grdGroupeSoftware1.Visible = false;
            grdEquipment.Visible = false;
            return;
        }
        Session["whereClause"] = GetWhereClause();
        txtHiddenWhereClause.Text = Session["whereClause"].ToString();
        Session["defaultTabIndex"] = 0;
        ClearSearchedTextBoxes();
        
    }
    private void ClearSearchedTextBoxes()
    {
        txtWorkOrder.Text = string.Empty;
        txtTaskId.Text = string.Empty;
        txtPreventive.Text = string.Empty;
        txtPlanDate.Text = string.Empty;
        
    }
   
    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";
        if (drlEmployee.SelectedIndex > 0)
        {
            str = " (Employee.EmployeeId =" + this.drlEmployee.SelectedValue + ")";
            and = " and ";
        }



        if (txtPlanDate.Text != string.Empty)
        {

            str += and + "( PLANNING.PLANDATE=convert(datetime,'" + txtPlanDate.Text + "', 101) )";
            and = " and ";

        }
        if (txtWorkOrder.Text != string.Empty)
        {

            str += and + "( TASKINWORKORDER.WORKORDERID =" +txtWorkOrder.Text+ ")";
            and = " and ";

        }
        if (txtTaskId.Text != string.Empty)
        {
            str += and + "( PLANNING.TASKINWORKORDERID =" + txtTaskId.Text + ")";
            and = " and ";

        }
        if(chkPreventive.Checked)
        {
            if (!String.IsNullOrEmpty(txtPreventive.Text))
            {
                str += and +
                       " (TASKINWORKORDER.cancel=0 and WORKORDER.WORKORDERID in (select workorderid from preventivemaintenance where preventivemaintenance.maintenanceid=" +
                       txtPreventive.Text + "))";
                and = " and ";
            }
        }
        if (chkNoActionTaken.Checked)
        {

            str += and + "  (planning.planningid not in(select planningid from reparation)) ";
            and = " OR ";
        }

            Utility _Utility = new Utility();
            if (chkCancel.Checked)
            {
                str += and + "(PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskCancel) +
                       " AND TASKSTATUSID " +
                       " IN (SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (chkCompleted.Checked)
            {
                str += and  +  " (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskCompleted) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (chkInProgress.Checked)
            {
                str += and  + "  (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskInProgressId) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (chkOpen.Checked)
            {
                str += and  + " (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskOpenId) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";


            }
            if (chkPending.Checked)
            {
                str += and  + " (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskPendingId) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (chkTest.Checked)
            {
                str += and + " (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskTest) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (chkNewComputer.Checked)
            {
                str += and + " (PLANNING.PLANNINGID IN( SELECT DISTINCT PLANNINGID FROM REPARATION  " +
                       " WHERE (TASKSTATUSID = " + _Utility.ConvertToInteger(Resources.Resource.TaskSetUpNewComputer) +
                       " AND TASKSTATUSID " +
                       "IN(SELECT DISTINCT MAX(TASKSTATUSID) FROM REPARATION GROUP BY PLANNINGID)))) ";
                and = " OR ";

            }
            if (!String.IsNullOrEmpty(str))
                whereClause += str + " ";
            else whereClause = " AND PLANNINGID  !=  0";
           
        return whereClause;
    }
    

    protected void odsSparepart_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        lblTotalEquipment.Text = "Total plannings : " +
                                 (e.ReturnValue != null
                                      ? ((DataTable) e.ReturnValue).Rows.Count.ToString()
                                      : 0.ToString());

        grdGroupeSoftware1.Visible = (e.ReturnValue == null
                                      ? true
                                      : ((DataTable) e.ReturnValue).Rows.Count ==0 ? true :false); 

    }
    protected void grdEquipment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int planningId = Convert.ToInt32(grdEquipment.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            txtHiddenPlanningId.Text = planningId.ToString();
            Session["planningId"] = planningId;
            Session["defaultTabIndex"] = 1;
            Session["rowSelectedIndex"] = Convert.ToInt32(e.CommandArgument);
        }
        new Utility().SetSelectedColorToGridView(e, grdEquipment);
        
        
    }


    protected void grdGroupeSoftware1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
